package  com.sxhalo.fsms.export;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class CreateSqlUtil {
	
	public static String getExportWhere(String[] columns, String search) {
		String where = "";
		if (!"".equals(search)) {
			for (int i = 0; i < columns.length; i++) {
				String colName = columns[i];
				if(colName.toLowerCase().contains("time")
					||colName.toLowerCase().contains("date")
					||colName.toLowerCase().contains("birthday")){
					if(isValidDate(search)){
						where += " or " + colName + " like '%" + search + "%'";
					}
				}else{
					where += " or " + colName + " like '%" + search + "%'";
				}
			}
			where = where.substring(3);
		}
		return where;
	}
	
	private static boolean isValidDate(String str) {
		boolean convertSuccess=true;
		// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(str.length()<17){
			format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		}
		if(str.length()<11){
			format = new SimpleDateFormat("yyyy-MM-dd");
		}
		if(str.length()<11){
			format = new SimpleDateFormat("yyyy-MM-dd");
		}
		if(str.length()<8){
			format = new SimpleDateFormat("yyyy-MM");
		}
		if(str.length()<5){
			format = new SimpleDateFormat("yyyy");
		}
		try {
			// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess=false;
		} 
		return convertSuccess;
	}
}
